/**
 * Copyright 2019-2024 覃海林(qinhaisenlin@163.com).
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */ 
package com.qinhailin.portal.core.service;

import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.List;

import com.alibaba.druid.filter.stat.StatFilter;
import com.alibaba.druid.wall.WallFilter;
import com.jfinal.kit.Ret;
import com.jfinal.plugin.activerecord.ActiveRecordPlugin;
import com.jfinal.plugin.activerecord.DbKit;
import com.jfinal.plugin.activerecord.Model;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.dialect.OracleDialect;
import com.jfinal.plugin.druid.DruidPlugin;
import com.qinhailin.common.model.DataSource;
import com.qinhailin.common.model._MappingKit;
import com.qinhailin.common.base.service.BaseService;
import com.qinhailin.common.vo.Grid;

/**
 * 数据源
 * @author qinhailin
 * @date 2022-11-26
 */
public class DataSourceService extends BaseService {
	private DataSource dao = new DataSource().dao();
	public static DataSourceService me=new DataSourceService();
	
    @Override
    public Model<DataSource> getDao(){
    	return dao;
    }


    public Grid page(int pageNumber, int pageSize,Record record) {
        Record rd = new Record();
        rd.set("title like", record.getStr("keyword"));
        return queryForList(pageNumber, pageSize,rd);
    }
       
    /**
     * 获取已启动的数据源
     * @param start 启动状态：0：未启动，1：已启动
     * @return
     */
	public List<DataSource> getDataSourceListByStart(int start){    	
    	return dao.find(getQuerySql("start"), start);
    }
        
    /**
     * 测试数据源链接是否正常
     * @param dataSource
     * @return
     */
    public Ret testDataSourceConnection(DataSource dataSource) {
    	try {
    		if(dataSource==null)
    			return Ret.fail("数据源不存在");
    		testConnection(dataSource.getJdbcUrl(), dataSource.getUser(), dataSource.getPassword());
    		return Ret.ok("测试连接成功");
		} catch (Exception e) {
			e.printStackTrace();
			return Ret.fail(e.getMessage());
		}
    }
    
    public void testConnection(String url,String user,String password) throws SQLException {
    	DriverManager.getConnection(url, user, password);
    }
    

    public Ret startDruidPlugin(DataSource dataSource) {
    	if(dataSource==null)
    		return Ret.fail("数据源不存在");
    	
    	Ret ret=testDataSourceConnection(dataSource);
		if(ret.isFail()) {
			dataSource.setStart(0).update();
			return ret;
		}
		
		DruidPlugin dbPlugin=new DruidPlugin(dataSource.getJdbcUrl(), dataSource.getUser(), dataSource.getPassword());
    	dbPlugin.addFilter(new StatFilter());
		WallFilter wallOracle = new WallFilter();
		wallOracle.setDbType(dataSource.getDbType());
		dbPlugin.addFilter(wallOracle);		
		// ActiveRecrodPlugin 实例，并指定configName
		ActiveRecordPlugin arp = new ActiveRecordPlugin(dataSource.getConfigName(), dbPlugin);
		if("oracle".equals(dataSource.getDbType())) {
			arp.setDialect(new OracleDialect());
		}
		_MappingKit.annotationTable(arp, dataSource.getConfigName());
		dbPlugin.start();	
		boolean b=arp.start();
		if(b) {
			dataSource.setStart(1).update();
			ret=Ret.ok("启动成功");
		}
		return ret;
    }
    
    public void startDruidPlugin() {
    	List<DataSource> list=dao.findAll();
    	for(DataSource dataSource:list) {
    		//重置启动状态
    		dataSource.setStart(0).update();
    		//启动数据源
    		if(dataSource.getState()==1)
    			startDruidPlugin(dataSource);
    	}
    }
    
    public void stopDruidPlugin() {
    	List<DataSource> list=getDataSourceListByStart(1);
    	for(DataSource dataSource:list) {
    		stopDruidPlugin(dataSource);
    	}
    }
    
    public Ret stopDruidPlugin(DataSource dataSource) {
    	DbKit.removeConfig(dataSource.getConfigName());
    	dataSource.setStart(0).update();
    	return Ret.ok("已停用");
    }
}
